<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, getCurrentInstance, onMounted, reactive, nextTick, computed, watch } from 'vue';
import { Check, Delete, Edit, Message, Search, Star } from '@element-plus/icons-vue';
import api from '@/api'; // 统一导入 API

const { proxy } = getCurrentInstance();

// 数据定义
const salesData = ref([]); // 左边表单数据
const RemarkFormField = ref(''); // 备注字段数据
const inventoryList = ref([]); // 库存数据
const formInline = reactive({ 
    productCode: '',
    skuCode: '' 
}); // 搜索内容
const config = reactive({ 
    page: 1, 
    pageSize: 30, 
    productCode: '',
    skuCode: ''
}); // 分页和搜索配置
const totalCount = ref(0); // 总数
const totalRetailPrice = ref(0.0); // 吊牌金额
const discount = ref(0.0); // 优惠金额
const totalActualSellingPrice = ref(0.0); // 实销金额
const editTotalActualSellingPrice = ref(0.0); // 编辑后的实销金额
const editUniformDiscount = ref(1); // 统一折扣
const selectedRows = ref([]); // 选中的行
const multipleTable = ref(null); // 表格实例

// 表格列配置
const tableLabel = reactive([
  { prop: 'brand', label: '品牌' },
  { prop: 'productCode', label: '商品款号' },
  { prop: 'retailPrice', label: '零售价' },
  { prop: 'color', label: '颜色' },
  { prop: 'sizeType', label: '尺码类型' },
  { prop: 'skuCode', label: '条形码' },
  { prop: 'discount', label: '折扣' },
  { prop: 'actualPrice', label: '实销价' },
]);

// 计算属性：过滤库存数据
const filteredInventory = computed(() => {
  return inventoryList.value.filter((item) => item.status === 1);
});

// 获取库存数据
const getInventoryList = async () => {
  try {
    const data = await api.storeCashier.getStoreCashierInventoryList(config);
    inventoryList.value = data.records;
    config.total = data.total;
  } catch (error) {
    ElMessage.error('获取库存数据失败，请稍后再试');
  }
};

// 扫码输入框引用
const skuInputRef = ref(null);

// 本地搜索商品
const searchLocalBySku = (skuCode) => {
    return inventoryList.value.find(item => item.skuCode === skuCode);
};

// 处理扫码输入
const handleSkuInput = async (e) => {
    if (e.key === 'Enter') {
        const skuCode = formInline.skuCode.trim();
        if (!skuCode) return;

        // 先在本地库存中搜索
        const localItem = searchLocalBySku(skuCode);
        if (localItem) {
            transferToSalesData(localItem);
            formInline.skuCode = ''; // 清空输入框
            return;
        }

        // 本地没找到，则调用后端API搜索
        try {
            config.skuCode = skuCode;
            config.productCode = '';  // 清空商品款号搜索
            await getInventoryList();
            formInline.skuCode = ''; // 清空输入框
        } catch (error) {
            ElMessage.error('商品不存在');
        }
    }
};

// 修改搜索处理方法
const handleSearch = () => {
    // 清理输入，将只包含空格的字符串视为空字符串
    formInline.productCode = formInline.productCode.trim() || '';
    formInline.skuCode = formInline.skuCode.trim() || '';
    config.productCode = formInline.productCode;
    config.skuCode = formInline.skuCode;
    getInventoryList();
};

// 处理分页变化
const handleSizeChange = (pageSize) => {
    config.pageSize = pageSize
    getInventoryList()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
    config.page = page
    getInventoryList()
}

// 获取所有选中的行
const getSelectedRows = () => {
    return multipleTable.value.getSelectionRows()
}

// 处理选中行变化
const handleSelectionChange = (selection) => {
    selectedRows.value = multipleTable.value.getSelectionRows()
}

// 批量删除
const handleBatchDelete = async () => {
    selectedRows.value = getSelectedRows();
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的行');
        return;
    }
    const ids = selectedRows.value.map(row => row.id);

    try {
        await ElMessageBox.confirm('请确定是否批量删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        const updatedSalesData = salesData.value.filter(item => !ids.includes(item.id));
        salesData.value = updatedSalesData;

        // 更新 inventoryList
        ids.forEach(id => {
            const inventoryItem = inventoryList.value.find(item => item.id === id);
            inventoryItem.inventory += 1;
        });

        ElMessage({
            type: 'success',
            message: '删除成功!',
        });
        updateBottomInfo();
    } catch (error) {
        ElMessage.error('删除失败: ' + (error && error.message || '未知错误'));
    }
};

// 选中右边商品进入左边销售表单
const transferToSalesData = (item) => {
    // 查找库存列表中对应 id 的商品
    const inventoryIndex = inventoryList.value.findIndex(inv => inv.pdId === item.pdId);
    inventoryList.value[inventoryIndex].status = 0;

    // 检查是否有实销价，如果没有则设置为吊牌价
    if (!item.actualPrice || item.actualPrice <= 0) {
        item.actualPrice = item.retailPrice;
    }

    if (inventoryIndex !== -1) {
        const inventoryItem = inventoryList.value[inventoryIndex];
        inventoryItem.inventory -= 1;

        // 创建一个新的销售数据对象
        const newSalesData = { 
            ...item, 
            pdId: inventoryItem.pdId,
            discount: 1 // 默认无折扣
        };
        salesData.value.push(newSalesData);

        updateBottomInfo();
        ElMessage.success('商品已成功添加到销售列表！');
    } else {
        ElMessage.error('未找到该商品在库存中的记录！');
    }
}

// 删除
const handleDelete = (val) => {
    ElMessageBox.confirm("你确定要删除吗?").then(async () => {
        console.log('handleDelete中要删除的项对应的id', val.row.id);
        const index = salesData.value.findIndex(item => item.id === val.row.id);
        if (index !== -1) {
            // 从 salesData 中删除该项
            salesData.value.splice(index, 1);

            // 更新 inventoryList
            const inventoryItem = inventoryList.value.find(item => item.id === val.row.id);
            inventoryItem.inventory += 1;

            // 显示删除成功的消息
            ElMessage({
                showClose: true,
                message: '删除成功',
                type: 'success'
            });
            updateBottomInfo();
        } else {
            // 如果未找到对应的项，显示错误消息
            ElMessage.error('未找到要删除的销售记录！');
        }
    }).catch(() => {
        // 用户取消删除操作，不执行任何操作
    });
};

// 更新底部统计信息
const updateBottomInfo = () => {
    let totalRetailSum = 0.00;
    let totalActualSaleSum = 0.00;

    salesData.value.forEach(item => {
        const retailPrice = parseFloat(item.retailPrice) || 0.00;
        const actualPrice = parseFloat(item.actualPrice) || 0.00;
        totalRetailSum += retailPrice; // 累加吊牌金额
        totalActualSaleSum += actualPrice; // 累加实销价
        item.discount = ((actualPrice / retailPrice)).toFixed(2);
    });

    totalCount.value = salesData.value.length;
    totalRetailPrice.value = totalRetailSum.toFixed(2);
    discount.value = (totalRetailSum - totalActualSaleSum).toFixed(2);
    totalActualSellingPrice.value = totalActualSaleSum.toFixed(2);
    editTotalActualSellingPrice.value = totalActualSellingPrice.value
};

// 左侧底部清空按钮方法
const handleClear = () => {
    salesData.value = []; // 清空销售数据
    selectedRows.value = []; // 清空选中的行
    RemarkFormField.value = ''; // 清空备注字段
    getInventoryList()//更新右侧库存信息
    updateBottomInfo(); // 更新底部统计信息
    ElMessage.success('销售数据已清空！');
};

const handleEditTotalActualSellingPrice = () => {
    // 检查是否避免了除以零的情况
    if (totalActualSellingPrice.value === 0) {
        ElMessage.error("当前无销售记录，不能执行操作")
        return;
    }
    if (editTotalActualSellingPrice.value <= 0) {
        ElMessage.error("不能<=0")
        return;
    }

    // 计算比例并更新每条数据的实销价
    const ratio = editTotalActualSellingPrice.value / totalActualSellingPrice.value;
    //修改统一折扣
    editUniformDiscount.value = ratio.toFixed(2);
    salesData.value = salesData.value.map(item => ({
        ...item,
        actualPrice: (item.actualPrice * ratio).toFixed(2)
    }));
    updateBottomInfo();
};

// 左侧底部折扣按钮：修改折扣功能
const handleEditUniformDiscount = () => {
    if (totalActualSellingPrice.value === 0) {
        ElMessage.error("当前无销售记录，不能执行操作");
        return;
    }
    if (editUniformDiscount.value > 1) {
        ElMessage.error("折扣不能 > 1");
        return;
    }

    // 将编辑的折扣转换为小数形式，例如0.8代表8折
    const newDiscount = editUniformDiscount.value;

    // 更新每条数据的折扣和实销价
    salesData.value = salesData.value.map(item => ({
        ...item,
        discount: newDiscount, // 转换回百分比形式存储
        actualPrice: (item.retailPrice * newDiscount).toFixed(2) // 应用新的折扣计算实销价
    }));
    updateBottomInfo();
};

const onSubmit = async () => {
    console.log('提交前formSale:', formSale)
    // 遍历salesData，更新符合id的项的color
    salesData.value.forEach(sale => {
        if (sale.color === formSale.oldColor && sale.isOpen == true) {
            sale.color = formSale.color ? formSale.color : null;
            sale.sizeType = formSale.sizeType ? formSale.sizeType : null
            sale.id = formSale.id
            sale.pdId = formSale.pdId
            sale.isOpen = false
            console.log('编辑界面提交,sale:', sale)
        }
    })
    // 关闭对话框（新增/修改页面）
    dialogVisible.value = false
    ElMessage.success("修改成功")
};

// 结算功能
const handleSettlement = async () => {
  try {
    // 1. 数据校验
    if (salesData.value.length === 0) {
      ElMessage.warning('没有可结算的商品');
      return;
    }

    // 2. 构建结算数据
    const settlementData = {
      items: salesData.value.map(item => ({
        id: item.id,
        pdId: item.pdId,
        actualPrice: Number(item.actualPrice).toFixed(2),
      })),
      totalActualPrice: totalActualSellingPrice.value,
      totalRetailPrice: totalRetailPrice.value,
      total: totalCount.value,
      remark: RemarkFormField.value
    };

    // 3. 数据完整性检查
    const invalidItems = settlementData.items.filter(item => 
      !item.pdId || isNaN(item.actualPrice)
    );
    
    if (invalidItems.length > 0) {
      ElMessage.error('存在无效的销售数据，请检查商品信息');
      return;
    }

    // 4. 确认对话框
    await ElMessageBox.confirm(
      `确定要结算 ${totalCount.value} 件商品吗？实销总金额：￥${totalActualSellingPrice.value}`,
      '结算确认',
      {
        confirmButtonText: '确定结算',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 5. 调用API

      const response = await api.settlement.submitSettlement(settlementData);
      ElMessage.success('结算成功！');
      // 清空数据
      handleClear();
      // 刷新库存
      getInventoryList();
      
    
  } catch (error) {
    ElMessage.error(`结算失败：${error.message || '未知错误'}`);
  }
};


// 生命周期钩子
onMounted(() => {
    getInventoryList()
    // 自动聚焦到扫码输入框
    nextTick(() => {
        skuInputRef.value?.focus();
    });
})
</script>

<template>
    <el-row class="BatchOutbound" :gutter="20" style="height: 100%; overflow-y: auto;">
        <!-- 左部分 -->
        <el-col :span="16" style="margin-top: 20px;" class="left" highlight-current-row>
            <el-row class="salesItem">
                <div class="table">
                    <el-empty v-if="salesData.length === 0" description="未查询到销售信息" />
                    <el-table v-else 
                        :data="salesData"  highlight-current-row style="width: 100%" 
                        :multi-select="true"
                        ref="multipleTable" @selection-change="handleSelectionChange" size="large" 
                        scroll-y
                        >
                        <el-table-column type="selection" width="50" />
                        <el-table-column type="index" width="50" />
                        <el-table-column v-for="item in tableLabel" :key="item.prop" :width="item.width || 125"
                            :prop="item.prop" :label="item.label" />
                        <!-- 操作按钮 -->
                        <el-table-column fixed="right" label="操作" min-width="120">
                            <template #default="scope">
                                <el-button type="danger" :icon="Delete" circle size="default"
                                    @click="handleDelete(scope)" />
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-row>
            <el-scrollbar height="38%">
                <el-row class="remark">
                    <el-text>备注：</el-text>
                    <el-input class="remark-input" placeholder="" type="textarea" :autosize="{ minRows: 1, maxRows: 2 }"
                        v-model="RemarkFormField" />
                </el-row>

                <el-row class="bottom">
                    <div class="priceDetail">
                        <div class="bottom-left">
                            总数：<span class="totalCount">{{ totalCount }}</span>
                            吊牌金额：<span>￥{{ totalRetailPrice }}</span>
                        </div>
                        <div class="bottom-right">
                            <el-popover placement="top-start" title="Title" :width="200" trigger="hover"
                                content="优惠=实销价-吊牌价总额">
                                <template #reference>
                                    <el-button class="m-2"><el-icon size="large" style="color: #dcdcdc;">
                                            <View />
                                        </el-icon></el-button>
                                </template>
                            </el-popover>
                            优惠：￥<span>{{ discount }}</span>
                            <div class="totalActualSellingPrice">
                                ￥
                                <span>{{ totalActualSellingPrice }}</span>
                                <el-popover placement="top" :width="80" trigger="click">
                                    <template #reference>
                                        <el-button :icon="Edit" size="small" />
                                    </template>
                                    <div style="display: flex;justify-content: center;">
                                        <el-input type="input" v-model="editTotalActualSellingPrice"
                                            style="width: 100px;" placeholder="请输入实销价" />
                                        <el-button type="success" :icon="Check" style="margin-left: 4px;" circle
                                            size="small" @click="handleEditTotalActualSellingPrice" />
                                    </div>
                                </el-popover>
                            </div>
                        </div>
                    </div>
                    <div class="Operations">
                        <el-button plain @click="handleClear">清空</el-button>
                        <el-button type="danger" plain @click="handleBatchDelete">批量删除</el-button>

                        <el-popover placement="top" :width="160" trigger="click">
                            <template #reference>
                                <el-button type="warning" plain>折扣</el-button>
                            </template>
                            <el-input type="input" v-model="editUniformDiscount" placeholder="请输入小数"
                                style="width: 100px;" />
                            <el-button type="success" :icon="Check" style="margin-left: 4px;" circle size="small"
                                @click="handleEditUniformDiscount" />
                        </el-popover>

                        <el-button type="primary" plain @click="handleSettlement">结算</el-button>
                    </div>
                </el-row>
            </el-scrollbar>
        </el-col>
        <!-- 右边部分 -->
        <el-col :span="8" style="margin-top: 20px;" class="right">
            <div class="Inventory-header">
                <el-form :inline="true" :model="formInline">
                    <el-form-item label="条形码:" class="sku-input">
                        <el-input 
                            ref="skuInputRef"
                            v-model="formInline.skuCode" 
                            placeholder="扫描或输入条形码"
                            @keyup="handleSkuInput"
                            clearable>
                            <template #prefix>
                                <el-icon><Scan /></el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="商品款号:">
                        <el-input placeholder="请输入商品款号" v-model="formInline.productCode" @input="handleSearch" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div v-if="inventoryList.length === 0" class="no-cards">
                <el-empty description="未查询到库存商品" />
            </div>
            <div v-else class="card-list">
                <el-scrollbar height="90%">
                    <div class="card-list">
                        <el-card v-for="item in filteredInventory" :key="item.id" :body-style="{ padding: '2px' }">
                            <div class="card-header">
                                <div class="brand-code">
                                    <span class="brand">{{ item.brand }}</span>
                                    <span class="productCode">{{ item.productCode }}</span>
                                </div>
                                <span class="color">{{ item.color }}</span>
                            </div>
                            <div class="card-body">
                                <div class="sku-info">
                                    <span class="sku-code">SKU: {{ item.skuCode }}</span>
                                    <span class="size-type">{{ item.sizeType }}</span>
                                </div>
                                <div class="price-section">
                                    <span class="retailPrice">￥{{ item.retailPrice }}</span>
                                    <el-button link type="primary" @click="transferToSalesData(item)">选择</el-button>
                                </div>
                            </div>
                        </el-card>
                    </div>
                </el-scrollbar>
            </div>
            <el-pagination 
                v-model:current-page="config.page" v-model:page-size="config.pageSize" 
                :page-sizes="[30, 40]"
                size="small" layout="total, sizes, prev, pager, next, jumper" 
                :total="config.total" background
                @size-change="handleSizeChange" @current-change="handleCurrentChange" 
                />
        </el-col>
    </el-row>
</template>

<style scoped lang="less">
.BatchOutbound {
    height: 100%;
    overflow: hidden;

    // 左部分样式
    .left {
        height: 100%;
        overflow: hidden;

        .salesItem {
            width: 100%;
            height: 65%;
            background-color: #fff;

            .table {
                height: 100%;
                position: relative;
                border: 1px solid #dcdcdc;
                width: 100%;
                overflow: auto;

                .el-table {
                    width: 100%;
                }
            }
        }

        .remark {
            border: 1px solid #dcdcdc;
            padding: 10px 20px;
            background-color: #fff;
            overflow: auto;

            .remark-input {
                width: 1200px;

                .el-textarea__inner {
                    border: none;
                    outline: none;
                    width: 100%;
                }
            }
        }

        .bottom {
            border: 1px solid #dcdcdc;
            border-top: 0;
            padding: 16px 20px;
            font-weight: 800;
            display: block;
            font-size: 18px;
            background-color: #fff;
            overflow: auto;

            .priceDetail {
                display: flex;
                justify-content: space-between;

                .bottom-left {
                    .totalCount {
                        margin-right: 30px;
                    }
                }

                .bottom-right {
                    display: block;
                    color: #FFA500;

                    .m-2 {
                        padding: 0;
                        border: 0;
                    }

                    .totalActualSellingPrice {
                        margin-top: 20px;
                        font-size: 30px;

                        .el-button {
                            border: 0;
                            margin-left: 10px;
                            font-size: 20px;
                            padding: 0;
                        }
                    }
                }
            }

            .Operations {
                display: flex;
                justify-content: center;
                margin-top: auto;
            }
        }
    }

    // 为右部分添加背景颜色或边框
    .right {
        height: 100%;
        overflow: hidden;

        .Inventory-header {
            display: flex;
            justify-content: space-between;
        }

        .card-list {
            height: calc(100% - 120px);
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            overflow: auto;
        }

        .el-card {
            width: 200px;
            margin-bottom: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            overflow: hidden;
            cursor: pointer;

            .card-header {
                padding: 8px 12px;
                border-bottom: 1px solid #f0f0f0;

                .brand-code {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 4px;

                    .brand {
                        font-size: 12px;
                        color: #666;
                    }

                    .productCode {
                        font-size: 16px;
                        color: #FFA500;
                        font-weight: bold;
                    }
                }

                .color {
                    font-size: 12px;
                    color: #666;
                }
            }

            .card-body {
                padding: 8px 12px;

                .sku-info {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 8px;

                    .sku-code {
                        font-size: 14px;
                        color: #333;
                    }

                    .size-type {
                        font-size: 14px;
                        color: #409EFF;
                        font-weight: bold;
                    }
                }

                .price-section {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    .retailPrice {
                        font-size: 16px;
                        color: #f56c6c;
                        font-weight: bold;
                    }
                }
            }

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
            }
        }
    }
}

.Inventory-header {
    .sku-input {
        .el-input {
            width: 200px;
        }
    }
}
</style>